#include "CommandLineArguments.h"
#include <iostream>
using std::cout;

CommandLineArguments &CommandLineArguments::GetInstance()
{
	static CommandLineArguments instance;
	return instance;
}

CommandLineArguments::CommandLineArguments()
{

}

void CommandLineArguments::Add(char *_szArg, char *_szDescription, CLA_Callback _pCallback)
{
	Argument newArg = {_szArg, _szDescription, NULL, _pCallback };
	m_ArgumentList.push_back(newArg);
}

bool CommandLineArguments::Parse(int argc, char **argv)
{
	int numOfArgs = m_ArgumentList.size();

	for (int i = 1; i < argc; ++i)
	{
		if (argv[i][0] == m_prefix)
		{
			int iArg;
			for (iArg = 0; iArg < numOfArgs; ++iArg)
			{
				if (_stricmp(m_ArgumentList[iArg].szArg, argv[i] + 1) == 0)
				{
					if (i + 1 < argc && argv[i + 1][0] != m_prefix)
					{
						++i;
						m_ArgumentList[iArg].szValue = (argv[i] + 1);
					}
					else
					{
						m_ArgumentList[iArg].szValue = "True";
					}

					if (m_ArgumentList[iArg].pCallback(m_ArgumentList[iArg].szValue) == false)
					{
						if (m_ArgumentList[iArg].pCallback != PrintHelp)
							cout << "Command line argument " << m_ArgumentList[iArg].szArg << "'s value was not accepted.\n";
						return false;
					}
					break;
				}
			}

			if (iArg == numOfArgs)
			{
				cout << argv[i] << " is not a valid argument.\n";
				return false;
			}
		}
	}

	return true;
}

bool PrintHelp(char *)
{
	CommandLineArguments &CLA = CommandLineArguments::GetInstance();
	int numOfArgs = CLA.m_ArgumentList.size();
	for (int iArg = 0; iArg < numOfArgs; ++iArg)
	{
		cout << CLA.m_prefix << CLA.m_ArgumentList[iArg].szArg << '\t' << CLA.m_ArgumentList[iArg].szDescription << '\n';
	}

	return false;
}